import {Component, OnInit} from '@angular/core';
import {BarnSystemInfo} from "../entity/barn-system-info";
import {SystemInfoService} from "../service/system-info.service";
import {NzMessageService} from "ng-zorro-antd/message";

@Component({
  selector: 'app-system-info',
  templateUrl: './system-info.component.html',
  styleUrls: ['./system-info.component.less']
})
export class SystemInfoComponent implements OnInit {

  variable: BarnSystemInfo[]
  isFolded = true
  filter: string
  loading = false

  constructor(private systemInfoService: SystemInfoService, private msg: NzMessageService) {
  }

  ngOnInit(): void {
    this.variable = BarnSystemInfo.variables();
    this.foldedPanel()
    this.query()
  }

  foldedPanel() {
    for (let i = 0; i < this.variable.length; i++) {
      this.variable[i].isFolded = this.isFolded
    }
  }

  foldBtnEvent(isFold: boolean) {
    this.isFolded = isFold
    this.foldedPanel()
  }

  get computedVariable():BarnSystemInfo[] {
    if (!this.filter) {
      return this.variable
    }
    const result = [];
    for (let i = 0; i < this.variable.length; i++) {
      if (this.variable[i].pid.indexOf(this.filter) >= 0) {
        result.push(this.variable[i])
      } else if (this.variable[i].variableName.indexOf(this.filter) >= 0) {
        result.push(this.variable[i])
      }
    }

    return result;
  }

  save(value: BarnSystemInfo) {
    if (value.variableValue.length >= 100) {
      this.msg.error("数据过长，最长100个字符")
      return;
    }
    this.loading = true;
    this.systemInfoService.save(value).subscribe(v => {
      this.loading = false
      this.msg.success("保存成功")
    }, () => this.loading = false)
  }

  query() {
    this.loading = true
    this.systemInfoService.query(null).subscribe(value => {
      this.loading = false
      if (value && value.length) {
        for (let i = 0; i < value.length; i++) {
          const v = this.variable.find(e => e.pid === value[i].pid);
          if (v) {
            v.variableValue = value[i].variableValue
          }
        }
      }
    }, error => this.loading = false)

  }

}
